<?php
namespace app\mbti\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Mbti;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Db;
use think\Session;
use think\Validate;
use GuzzleHttp\Client;

/**
 * 测评中心
 */
class Evaluate extends Mbti
{
    protected $layout = '';
    protected $noNeedLogin = ['index', 'show_result', 'update_wx_applet'];//实际上是都需要登录只是不用父类的跳转登录逻辑
    protected $noNeedRight = ['*'];

    /**
     * MbtiScene场景模型对象
     * @var \app\mbti\model\MbtiScene
     */
    protected $sceneModel = null;
    /**
     * MbtiResult场景结果模型对象
     * @var \app\mbti\model\MbtiResult
     */
    protected $resultModel = null;
    /**
     * MbtiEvaluate测评结果模型对象
     * @var \app\mbti\model\MbtiEvaluate
     */
    protected $evaluateModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->sceneModel = new \app\mbti\model\MbtiScene;
        $this->resultModel = new \app\mbti\model\MbtiResult;
        $this->evaluateModel = new \app\mbti\model\MbtiEvaluate;
        $this->view->assign("viewStatusList", $this->evaluateModel->getViewStatusList());
    }

    public function index(){
        $sceneId = $this->request->param('scene_id', 0, 'intval');
        $sex = $this->request->param('sex', 'male');
        $birthday = $this->request->param('birthday', date('Y-m-d', strtotime('-5 years', time())));
        $scene = $this->sceneModel->where(["id" => $sceneId, "status" => "normal"])->find();
        $userInfo = $this->auth->getUser();
        if(!$scene){
            $this->error("场景不存在或已被禁用", url('mbti/index/index'));
        }
        $tempConfig = config('mbti_' . $scene["version"]);
        $questionList = $tempConfig['qs'];
        $aList = $tempConfig['a'];
        $bList = $tempConfig['b'];
        $evaluateInfo = $this->evaluateModel->where(['scene_id' => $scene["id"], 'user_id' => $userInfo["id"]])->field("id,answers")->find();
        $answers = $evaluateInfo ? ( count(unserialize($evaluateInfo['answers'])) == count($questionList) ? unserialize($evaluateInfo['answers']) : [] ) : [];
        if($this->wxConfig){
            $this->assignconfig('wx_config', $this->wxConfig);
        }
        config('url_common_param', true);
        $url = url('mbti/index/detail', ['scene_id' => $sceneId], true, true);
        config('url_common_param', false);
        $wxSite = [
            "title" => $scene['share_title'],
            "desc" => $scene['share_desc'],
            "link" => $url,
            "imgUrl" => cdnurl($scene['share_logo'], $this->request->domain())
        ];
        $this->assignconfig('wx_share', $wxSite);
        $this->assign("scene", $scene);
        $this->assign("title", $scene["name"]."-测评");
        $this->assign('questionList', $questionList);
        $this->assign('aList', $aList);
        $this->assign('bList', $bList);
        $this->assign('answers', $answers);
        $this->assign("scene_id", $scene["id"]);
        $this->assign("evaluate_id", $evaluateInfo ? $evaluateInfo['id'] : 0);
        $this->assignconfig("applet_path", config("site.applet_path"));
        $this->assignconfig("scene_id", $scene["id"]);
        $this->assignconfig("sex", $sex);
        $this->assignconfig("birthday", $birthday);
        $this->assignconfig("evaluate_id", $evaluateInfo ? $evaluateInfo['id'] : 0);
        return $this->view->fetch();
    }

    public function add_record(){
        $postData = $this->request->post();
        config("default_return_type", "json");
        $sceneVersion = $this->sceneModel->where(["id" => intval($postData["scene_id"]?:0)])->value("version");
        $tempConfig = config('mbti_' . $sceneVersion);
        $c = $tempConfig['c'];
        $answerArr = $postData["answers"];
        $groupData = [
            "E"=> 0, "I"=> 0,
            "S"=> 0, "N"=> 0,
            "T"=> 0, "F"=> 0,
            "J"=> 0, "P"=> 0
        ];
        foreach ($answerArr as $key => $item) {
            $dic = $c[$key][$item];
            $groupData[$dic] += 1;
        }
        try{
            $userInfo = $this->auth->getUser();
            $evaluateId = intval($postData["id"]?:0);
            $data = [
                'scene_id' => intval($postData["scene_id"]?:0),
                'user_id' => $userInfo["id"],
                'answers' => serialize($postData["answers"]),
                'sex' => $postData["sex"],
                'birthday' => $postData["birthday"],
                'mbti_ie' => $groupData['E'] > $groupData['I'] ? "E" : "I",
                'mbti_sn' => $groupData['S'] > $groupData['N'] ? "S" : "N",
                'mbti_tf' => $groupData['T'] > $groupData['F'] ? "T" : "F",
                'mbti_pj' => $groupData['J'] > $groupData['P'] ? "J" : "P",
                'updatetime' => time()
            ];
            if($evaluateId == 0){
                $data['applet_id'] = '';
                $data['view_status'] = 'create';
                $data['createtime'] = time();
                $evaluateId = $this->evaluateModel->insertGetId($data);
            }else{
                $this->evaluateModel->where(['id'=>$evaluateId])->update($data);
            }
            Db::name("user")->where(["id" => $userInfo["id"]])->update(["birthday" => $postData["birthday"]]);
            return ["code"=>"1","msg"=>"操作成功", "data"=>$evaluateId];
        }catch (\Exception $e){
            return ["code"=>"0", "msg"=>$e->getMessage(), "data"=>"操作失败"];
        }
    }

    //小程序内使用webview显示测评结果
    public function show_result(){
        $sceneId = $this->request->param('scene_id', 0, 'intval');
        $openId = $this->request->param('openid', "", 'trim');
        $unionId = $this->request->param('unionid', "", 'trim');
        $evaluateId = $this->request->param('evaluate_id', 0, 'intval');
        config('url_common_param', true);
        $url = url('mbti/evaluate/show_result', ["scene_id" => $sceneId, "evaluate_id" => $evaluateId, "unionid" => $unionId, "openid" => $openId], true, true);
        $shareUrl = url('mbti/index/detail', ['scene_id' => $sceneId], true, true);
        config('url_common_param', false);
        if (!$this->auth->isLogin()) {
            $config = get_addon_config('third');
            if (!$config['status']) {
                $this->redirect(url('mbti/user/login', ['url'=>$url], true, true));
            }else{
                $statusArr = explode(',', $config['status']);
                if(in_array('wechat', $statusArr)){
                    if(\addons\third\library\Service::isWechat()){
                        $this->redirect(url('third/connect/wechat', ['url'=>$url], true, true));
                    }else{
                        $this->redirect(url('mbti/user/login', ['url'=>$url], true, true));
                    }
                }
            }
        }
        try{
            $userInfo = $this->auth->getUser();
            $sceneInfo = $this->sceneModel->where(['id'=>$sceneId])->find();
            $evaluateInfo = $this->evaluateModel->where(['id'=>$evaluateId])->find();
            $baseUserInfo = Db::name("user")->where(["id"=>$evaluateInfo["user_id"]])->find();
            if($baseUserInfo["id"] == $userInfo["id"] && $unionId && $openId){
                \app\mbti\model\MbtiEvaluate::get(['id'=>$evaluateId])->save(["view_status"=>"read", "applet_id"=>$openId]);
            }
            $resultCondition = [
                'scene_id'=>$sceneInfo["id"],
                'sex'=>$evaluateInfo["sex"]
            ];
            if($evaluateInfo){
                $resultCondition['mbti_ie'] = ["IN", ["A", $evaluateInfo['mbti_ie']]];
                $resultCondition['mbti_sn'] = ["IN", ["A", $evaluateInfo['mbti_sn']]];
                $resultCondition['mbti_tf'] = ["IN", ["A", $evaluateInfo['mbti_tf']]];
                $resultCondition['mbti_pj'] = ["IN", ["A", $evaluateInfo['mbti_pj']]];
            }
            $resultInfo = $this->resultModel->where($resultCondition)->find();
            $colorConsts = config("color_solution");
            $colorSolution = $colorConsts[$resultInfo ? $resultInfo['color_solution'] : "group_0"];
            if($this->wxConfig){
                $this->assignconfig('wx_config', $this->wxConfig);
            }
            $wxSite = [
                "title" => $sceneInfo['share_title'],
                "desc" => $sceneInfo['share_desc'],
                "link" => $shareUrl,
                "imgUrl" => cdnurl($sceneInfo['share_logo'], $this->request->domain())
            ];
            $this->assignconfig('wx_share', $wxSite);
            $this->assign('title', $baseUserInfo["nickname"]);
            $this->assign('scene', $sceneInfo);
            $this->assign('base_user', $baseUserInfo);
            $this->assign('evaluate_info', $evaluateInfo);
            $this->assign('user_info', $userInfo);
            $this->assign('result_info', $resultInfo);
            $this->assign('color_solution', $colorSolution);
            $this->assignconfig("scene_id", $sceneId);
            $this->assignconfig("evaluate_id", $evaluateId);
            $this->assignconfig("color_solution", $colorSolution);
            return $this->view->fetch();
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
    }

    public function update_wx_applet(){
        config("default_return_type", "json");
        try {
            $appletUserInfo = $this->request->post();
            if(isset($appletUserInfo["union_id"])){
                $userId = Db::name("third")->where(["unionid" => $appletUserInfo["union_id"]])->value("user_id");
                $mpUserInfo = Db::name("user")->where(["id" => $userId])->find();
                if($mpUserInfo){
                    if(isset($appletUserInfo["phone"])){
                        Db::name("user")->where(["id" => $userId])->update(["mobile"=>$appletUserInfo["phone"]]);
                    }
                    $defaultAvatars = [
                        "https://cdn.xinnengliang.xin",
                        "https://cdn.xinnengliang.xin/mobileResources/defautAvatar.png",
                        "https://cdn.xinnengliang.xin/mobileResources/defaultAvatar.png"
                    ];
                    $defaultRealName = "微信用户".substr($appletUserInfo["we_chat_open_id"], -4, 4);
                    $defaultBirthDay = "";
                    $envNames = [
                        "dev" => "https://develop.xinnengliang.xin/psy/api",
                        "test"=>"https://trial.xinnengliang.xin/psy/api",
                        "pro"=>"https://test.xinnengliang.xin:7701/psy/api"
                    ];
                    $needUpdate = false;
                    if(array_search($appletUserInfo["avatar"], $defaultAvatars)){
                        $needUpdate = true;
                        $appletUserInfo["avatar"] = $mpUserInfo["avatar"];
                    }
                    if($appletUserInfo["realName"] == $defaultRealName){
                        $needUpdate = true;
                        $appletUserInfo["realName"] = $mpUserInfo["nickname"];
                        $appletUserInfo["nickname"] = $mpUserInfo["nickname"];
                    }
                    if($appletUserInfo["birthday"] == $defaultBirthDay){
                        $needUpdate = true;
                        $appletUserInfo["birthday"] = $mpUserInfo["birthday"];
                    }
                    $leaftoken = $this->request->header("leaftoken");
                    if($needUpdate && $leaftoken){
                        $client = new Client();
                        $envName = $appletUserInfo['envName'];
                        unset($appletUserInfo['envName']);
                        $response = $client->request('PUT',$envNames[$envName]."/basics/update/info", [
                            'headers' => [
                                'Content-Type' => 'application/json',
                                'Accept' => 'application/json',
                                'leaftoken' => $leaftoken
                            ],
                            'json' => $appletUserInfo,// 会自动编码为JSON并设置Content-Type
                            'timeout' => 30
                        ]);
                        $res = json_decode($response->getBody(), true);
                        if(is_array($res)){
                            $res["status_code"] = $response->getStatusCode();
                        }else{
                            $res = ["status_code" => $response->getStatusCode()];
                        }
                        return [
                            "code" => "0",
                            "message" => "操作成功",
                            'data' => $res
                        ];
                    }
                }
            }
            return [
                "code" => "0",
                "message" => "操作成功",
                "data" => []
            ];
        } catch (\Exception $e) {
            return [
                "code" => "0",
                "message" => "操作成功",
                "data" => ["res"=>$e->getMessage()]
            ];
        }
    }
}
